<style scoped lang="scss">

  .select_tree_box {
    position: relative !important;
    height: inherit;
    cursor: inherit;

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    .input_box {
      cursor: inherit;
      height: 100%;
      width: 100%;
      color: inherit;
      background-color: inherit;
      font: inherit;
      border: inherit;
      border-color: transparent;
      /*padding: 0 15px !important;*/
      text-indent: inherit;
      position: relative;
      /*user-select: none !important;*/
      overflow: hidden;
      outline: inherit;
      user-select: inherit;

      .input {
        width: calc(100% - 15px);
        height: 100%;
        border: none;
        font: inherit;
        color: inherit;
        background: inherit;
        outline: inherit;
        user-select: inherit;

        &:focus {
          box-shadow: none !important;
        }
      }

      .icon {
        position: absolute;
        right: 5px;
        top: calc(50% - 2px);
        border-color: black transparent transparent transparent;
        border-style: solid;
        border-width: 5px 3px 5px 3px;
        height: 0;
        width: 0;

        &.clear:hover {
          right: 2px;
          top: 50%;
          transform: translateY(-50%);

          width: 13px;
          height: 13px;
          border-radius: 50%;
          background-color: #f00;
          border-color: transparent;
        }
      }
    }

    .select_box {
      border: #000 1px solid;
      border-color: inherit;
      position: absolute;
      width: 100%;
      left: 0;
      z-index: 10;
      background: white;

      .search {
        outline: none;
        /*margin-top: 2px;*/
        border: none;
        border-bottom: 1px solid #000;
        border-color: inherit;
        width: 100%;
        height: 30px;
        font-size: 14px;
        padding: 0 10px;
        position: relative !important;

        &:focus {
          box-shadow: none !important;
        }
      }

      .select_tree_main {
        max-height: 200px;
        /*min-height: 26px;*/
        overflow-x: hidden;
        overflow-y: auto;
      }
    }
  }

</style>

<template>
  <div class="select_tree_box">
    <div class="input_box">
      <input readonly
             @click.stop="toggleShow"
             v-model="value[field.label]"
             :id="id+'_input'"
             type="text"
             class="input"
             :placeholder="placeholder">
      <div class="icon" @click="iconClick" :class="{clear:clearable&&value[field.id]}"></div>
    </div>
    <div v-show="show" class="select_box" :id="id">
      <input type="text" class="search" @input="input" placeholder="请输入关键字检索">
      <el-tree class="scroll_bar select_tree_main"
               ref="tree"
               v-if="treeData.length"
               :data="treeData"
               :node-key="field.id"
               @node-click="nodeClick"
               empty-text="没有数据"
               :filter-node-method="filterNode"
               :check-strictly="true"
               highlight-current
               :default-expanded-keys="defaultExpanded"
               :expand-on-click-node="expandOnClick"
               :render-content="renderContent">
      </el-tree>
    </div>
  </div>
</template>
<script>
  const { util } = require('../util')

  const { getRandomId } = util

  export default {
    name: 'selectTree',
    data () {
      return {
        id: getRandomId(10),
        show: false,
        treeData1: [],
        dataML: {},
        search: false,
        defaultExpanded: []
      }
    },
    async created () {
      // if (this.value[this.field.id]) this.defaultExpanded[0] = this.value[this.field.id];
    },
    mounted () {
      this.setSelectedNode(this.value[this.field.id])
    },
    methods: {
      mousedown (ev) {
        let el = ev.target
        if (el.id === this.id || el.id === this.id + '_input') return
        while ((el = el.parentElement)) if (el.id === this.id || el.id === this.id + '_input') return
        this.show = false
        window.removeEventListener('mousedown', this.mousedown)
      },
      iconClick () {
        if (this.clearable && this.value[this.field.id]) {
          this.setSelectedNode()
          this.$refs.tree.setCurrentNode({})
          this.$emit('input', {})
          this.$emit('selected', {})
        }
      },
      toggleShow () {
        this.show = !this.show
        if (this.show) {
          window.addEventListener('mousedown', this.mousedown)
          // let el = document.getElementById(this.defaultExpanded[0]);
          this.$nextTick(() => {
            this.setSelectedNode(this.value[this.field.id])
            // el && el.scrollIntoView({behavior: "smooth", block: "nearest", inline: "nearest"});
          })
        } else {
          window.removeEventListener('mousedown', this.mousedown)
        }
      },
      nodeClick (data, node) {
        if (this.expandOnClick && node.childNodes.length) return
        // this.$emit('update:selectData', data);
        this.$emit('input', data)
        this.show = false
        // this.defaultExpanded[0] = data[this.field.id];
        window.removeEventListener('mousedown', this.mousedown)
        this.$emit('selected', data)
      },
      input (ev) {
        let value = ev.target.value
        this.$refs.tree.filter(value)
      },
      filterNode (value, data) {
        if (!value) return true
        if (data[this.field.label].indexOf(value) !== -1) return true
        // let SZMs = this.$methods.makePy(data[this.field.label]);
        // for (let szm of SZMs) {
        //   if (szm.toLowerCase().indexOf(value.toLowerCase()) !== -1) return true;
        // }
        return false
      },
      renderContent (h, { node, data, store }) {
        return (
          <div class="nowrap" id={'unit_' + data[this.field.id]}>{data[this.field.label]}</div>)
      },

      /**
       * 根据id展开自身及父节点
       */
      expandNode (id, isScroll = true) {
        try {
          console.group(`展开节点【${id}】，并滚动到该节点位置`)
          let node = this.$refs.tree.getNode(id)
          if (!node) return console.log(`未找到id为的节点`)
          console.log('已找到要展开的节点', node.data[this.field.label])
          let _node = node
          // _node.expand();
          while ((_node = _node.parent)) {
            _node.expand()
          }
          console.log('已展开节点')
          let el = document.querySelector(`#unit_${id}`)
          isScroll && this.$nextTick(() => {
            el && el.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' })
            // el && el.scrollIntoView();
            console.log('滚动到节点位置')
          })
        } finally {
          console.groupEnd()
        }
      },
      setSelectedNode (id) {
        if (!id) return
        let tree = this.$refs.tree
        if (!tree) return
        let node = tree.getNode(id)
        if (!node) return
        this.expandNode(id)
        tree.setCurrentNode(node.data)
      }
    },
    props: {
      treeData: {
        type: Array,
        default: [],
        required: true
      },
      field: {
        default: function () {
          return {}
        }
      },
      expandOnClick: {
        type: Boolean,
        default: false
      },
      clearable: {
        type: Boolean,
        default: false
      },
      value: {
        type: Object,
        default: () => {
          return {}
        }
      },
      placeholder: {
        type: String,
        default: ''
      }
    }
  }
</script>
